<template>
  <div class="app-container">
    <a-title @clickPreview="preview" />
    <div class="tatletitle">
      <!--用户数据-->
      <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="100px">
        <el-form-item label="收资内容" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="最迟收资日期" prop="dateRange">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            size="small"
            style="width:240px"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button :disabled="archiveStatusDis" type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-dropdown trigger="click" @command="handleCommand" >
            <el-button type="primary" size="mini" plain :disabled="archiveStatusDis">
              导入模板
              <i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="a">标准模板</el-dropdown-item>
              <el-dropdown-item command="b">
                <el-upload
                  class="upload-demo"
                  ref="upload"
                  :show-file-list="false"
                  :before-upload="beforeUpload"
                  action="#"
                >自制模板</el-upload>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
          >导出自制模板</el-button>
        </el-col>
        <el-col :span="1.5"></el-col>
      </el-row>
      <el-table
        stripe
        v-loading="loading"
        :data="dataList"
        @selection-change="handleSelectionChange"
        @sort-change="tableSortChange"
        :default-sort="{prop: 'createTime', order: 'ascending'}"
      >
        <el-table-column type="selection" width="55" align="center" :selectable="checkSelect"></el-table-column>
        <el-table-column
          label="收资内容"
          align="left"
          prop="name"
          :sort-orders="['ascending', 'descending']"
          sortable="custom"
        />
        <el-table-column
          label="收资说明"
          align="left"
          prop="pickUpExplain"
          show-overflow-tooltip
          :sort-orders="['ascending', 'descending']"
          sortable="custom"
        />
        <el-table-column
          label="最迟收资日期"
          align="center"
          width="200"
          prop="lastDate"
          :sort-orders="['ascending', 'descending']"
          sortable="custom"
        >
          <template slot-scope="scope">
            <el-date-picker
              v-model="scope.row.lastDate"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-dd"
              @change="handleLastDate(scope.row)"
              :disabled="archiveStatusDis"
            />
          </template>
        </el-table-column>

        <el-table-column label="附件" align="left" width="400" prop="attachments">
          <template slot-scope="scope">
            <div v-for="item in scope.row.attachments" :key="item.fileId" class="fileTable">
              <el-tooltip class="item" effect="dark" :content="item.fileName" placement="top">
                <div class="fileTableTr" style="width:320px">{{ item.fileName }}</div>
              </el-tooltip>
              <div v-if="item.fileName">
                <a class="a-style" @click="downloadOne(item.fileId,item.fileName)">下载</a>
                <!-- <a class="a-style" :href="item.storagePath" :download="item.fileName">下载</a> -->
                <a class="a-style" @click="handlePreview(item)">预览</a>
              </div>
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column label="最迟收资日期" align="center" prop="lastDate">
          <template slot-scope="scope">
            <el-form>
              <el-form-item size="mini" align="center">
                <el-date-picker
                  clearable
                  size="small"
                  type="date"
                  v-model="scope.row.lastDate"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期"
                  @change="handleLastDate(scope.row)"
                ></el-date-picker>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>-->

        <!-- <el-table-column label="附件" align="center" prop="attachments">
          <template slot-scope="{row}">
            <el-form :model="row.id">
              <el-form-item size="mini">
                <p v-for="(item,index) in row.attachments" :key="index">
                  {{item.fileName}}
                  <a class="a-style">下载</a>
                  <a class="a-style">预览</a>
                </p>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>-->
        <el-table-column
          label="调研情况"
          align="left"
          prop="inveSurvey"
          :sort-orders="['ascending', 'descending']"
          sortable="custom"
          show-overflow-tooltip
        />
        <el-table-column
          label="收资人"
          align="center"
          prop="pickUpPerson"
          width="90"
          :sort-orders="['ascending', 'descending']"
          sortable="custom"
        />
        <el-table-column
          label="收资日期"
          align="center"
          width="100"
          prop="pickUpDate"
          :sort-orders="['ascending', 'descending']"
          sortable="custom"
        ></el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
          width="120"
          v-if="!archiveStatusDis"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
            >编辑</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="收资内容" prop="name">
          <el-input v-model="form.name" placeholder="请输入" />
        </el-form-item>

        <el-form-item label="收资说明" prop="pickUpExplain">
          <el-input v-model="form.pickUpExplain" type="textarea" placeholder="请输入" :autosize="{ minRows: 4}" />
        </el-form-item>

        <el-form-item label="最迟收资日期" prop="lastDate">
          <el-date-picker
            v-model="form.lastDate"
            clearable
            size="small"
            style="width: 200px"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
          />
        </el-form-item>
        <el-form-item label="附件" prop="attachments">
          <vue-uploader
            :single-type="false"
            v-if="open"
            :file-list="form.attachments"
            @changeFileData="changeFile"
            @removeFileList="removeFileList"
            :pathName="pathName"
          />
        </el-form-item>
        <el-form-item label="调研情况" prop="inveSurvey">
          <el-input v-model="form.inveSurvey" type="textarea" placeholder="请输入" :autosize="{ minRows: 4}"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="canClick">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 模板列表 -->
    <el-dialog :visible.sync="openTemplate" width="800px" :show-close="false">
      <el-form :model="formTemplateQuery" label-width="100px">
        <el-row>
          <el-col :span="18">
            <div class="grid-content bg-purple">
              <el-form-item label="模板名称" prop="name">
                <el-input v-model="formTemplateQuery.templateName" placeholder="请输入" />
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="grid-content bg-purple-light">
              <el-form-item>
                <el-button
                  type="primary"
                  icon="el-icon-search"
                  size="mini"
                  @click="handleQueryTemp"
                >查询</el-button>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <el-table v-loading="loading" :data="pickupTemplateList">
        <el-table-column label="模版名称" align="center" prop="templateName" />
        <el-table-column label="业务类别" align="center" prop="businessCategoryName" />
        <el-table-column label="创建时间" align="center" prop="createTime" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="templateImport(scope.row)"
              icon="el-icon-upload2"
            >导入</el-button>
            <el-button
              size="mini"
              type="text"
              @click="templatePreview(scope.row)"
              icon="el-icon-search"
            >在线预览</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="templateTotal>0"
        :total="templateTotal"
        :page.sync="formTemplateQuery.pageNum"
        :limit.sync="formTemplateQuery.pageSize"
        @pagination="getTemplateList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelTemplate">关 闭</el-button>
      </div>
    </el-dialog>
    <!-- 预览 -->
    <el-dialog :visible.sync="openPreview" width="80%">
      <iframe :src="manualPreviewUrl" frameborder="0" width="100%" height="700px"></iframe>
    </el-dialog>
  </div>
</template>
<script>
import {
  pickupList,
  addPickup,
  delPickup,
  exportPickupList,
  getPickupDetail,
  updatePickup,
  importData,
  importTemplate
} from "@/api/business/pickup";
import {
  getArchiveAllStatus,
} from '@/api/business/dataArchive';
import { listPickupTemplate } from "@/api/system/pickupTemplate";
import aTitle from "@/components/Title";
import vueUploader from "@/components/Uploader";
import moment from "moment";
export default {
  name: "pickupManage",
  components: {
    vueUploader,
    aTitle
  },
  data () {
    return {
      archiveStatusDis: false,
      manualPreviewUrl: null,
      openPreview: false,
      pathName: '',
      // 遮罩层
      loading: false,
      // 选中数组
      guids: [],
      titles: [],
      dateRange: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      templateTotal: 0,
      // 表格数据
      dataList: [],
      // 收资模板表格数据
      pickupTemplateList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        businessId: undefined
      },
      // 表单参数
      form: {},
      fileList: [],
      formTemplateQuery: {
        pageNum: 1,
        pageSize: 10,
        templateName: undefined,
        businessCategoryId: undefined
      }, // 模板弹框form
      // 表单校验
      rules: {
        name: [{ required: true, message: "文件名称不能为空", trigger: "blur" }]
      },
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openTemplate: false, // 模板弹框
      canClick: false,
    };
  },
  watch: {},
  created () {
    this.queryParams.businessId = this.$route.params.id;
    this.formTemplateQuery.businessCategoryId = this.$route.params.businessCategoryId;
    this.getList();
    this.getTemplateList();
    this.pathName = `TJECdocuments/${this.$route.params.id}/收资管理`;
    getArchiveAllStatus(this.queryParams.businessId).then(res => {
      if(res.data.archiveStatus == '1' || res.data.archiveStatus == '2'){
        this.archiveStatusDis = true;
      }
    })
  },
  mounted(){
    document.title=document.getElementById("businessNameTitle").innerHTML;
  },
  methods: {
    preview () {
      this.openPreview = true;
      this.manualPreviewUrl = `${this.previewUrl}${encodeURIComponent(
        `${this.operationManual}业务主页/收资管理.xlsx`
      )}&name=${encodeURIComponent("收资管理.xlsx")}`;
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.guids = selection.map(item => item.guid);
      this.titles = selection.map(item => item.name);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 模板列表搜索
    handleQueryTemp () {
      this.formTemplateQuery.pageNum = 1;name
      this.getTemplateList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm("queryForm");
      this.dateRange = [];
      this.handleQuery();
    },
    /** 查询归档模板列表 */
    getList () {
      this.loading = true;
      pickupList(this.addDateRange(this.queryParams, this.dateRange)).then(
        response => {
          if (response.code === 200 && response.rows.length > 0) {
            response.rows.forEach(item => {
              if (item.pickUpDate) {
                item.pickUpDate = moment(item.pickUpDate).format("YYYY-MM-DD");
              }
            });
          }
          this.dataList = response.rows;
          this.total = response.total;
          this.loading = false;

          this.dataList.map(item =>{
            item.attachments.some(list=>{
              if(list.archiveStatus == '1' || list.archiveStatus == '2'){
                return item.status = true
              }
            })
          })
        }
      );
    },
    // 获取模板列表
    getTemplateList () {
      this.loading = true;
      listPickupTemplate(this.formTemplateQuery).then(response => {
        this.pickupTemplateList = response.rows;
        this.templateTotal = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 取消按钮
    cancelTemplate () {
      this.openTemplate = false;
    },
    // 表单重置
    reset () {
      this.form = {
        guid: undefined,
        attachments: []
        // templateName: undefined
      };
      this.fileList = [];
      this.resetForm("form");
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset();
      this.open = true;
      this.title = "添加收资管理";
      this.canClick = false;
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.reset();
      const guid = row.guid || this.guids;
      getPickupDetail(guid).then(response => {
        if (response.code == 200 && response.data) {
          if (response.data.attachments) {
            response.data.attachmentIds = [];
            response.data.attachments.forEach(item => {
              response.data.attachmentIds.push(item.fileId);
            });
          }
        }
        this.fileList = response.data.attachmentIds;
        this.form = response.data;
        this.open = true;
        this.title = "修改收资管理";
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const guids = row.guid || this.guids;
      const titles = row.title || this.titles;
      this.$confirm("是否确认删除收资内容"+ titles +"及其附件?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function () {
          return delPickup(guids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function () { });
    },
    /** 导出按钮操作 */
    handleExport () {
      this.$confirm(
        "为避免导入时出错，自制模板仅供导入时使用，请勿修改！",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).then(() => {
        exportPickupList(
          this.addDateRange(this.queryParams, this.dateRange)
        ).then(res => {
          if (res.code === 200) {
            this.download(res.msg);
          }
        });
      });
    },
    downloadOne (id, name) {
      this.downloadBlob(id, name)
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.guid != undefined) {
            updatePickup(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            this.canClick = true;
            this.form.attachmentIds = this.fileList;
            this.form.businessId = this.$route.params.id;
            addPickup(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
              this.canClick = false;
            });
          }
        }
      });
    },
    beforeUpload (file) {
      let formData = new FormData();
      formData.append("file", file);
      formData.append("businessId", this.$route.params.id);
      if (
        file.name.split(".")[1] === "xlsx" ||
        file.name.split(".")[1] === "xls"
      ) {
        importData(formData).then(res => {
          this.msgSuccess("导入成功");
          this.$router.go(0);
        });
      } else {
        this.msgError("文件格式不正确");
      }
    },
    // 导入
    handleCommand (command) {
      if (command === "a") {
        this.openTemplate = true;
      }
    },
    templatePreview (row) {
      this.filePreview(
        row.attachmentList[0].fileName,
        row.attachmentList[0].storagePath
      );
    },
    templateImport (row) {
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 10;
      this.queryParams.name = undefined;
      this.queryParams.businessId = this.$route.params.id;

      this.dateRange = [];
      pickupList(this.addDateRange(this.queryParams, this.dateRange)).then(
        response => {
          if (response.total > 0) {
            this.$message({
              message: "已有收资目录存在，请清空后再导入标准模版!",
              type: "warning"
            });
            return false;
          } else {
            importTemplate(row.guid, this.$route.params.id).then(res => {
              if (res.code === 200) {
                this.msgSuccess(res.msg);
                this.getList();
              }
            });
          }
        }
      );
    },
    // 最迟收资日期选择
    handleLastDate (data) {
      data.flag = "1";
      updatePickup(data).then(response => {
        if (response.code === 200) {
          this.msgSuccess("修改成功");
          this.open = false;
          this.getList();
        } else {
          this.msgError(response.msg);
        }
      });
    },
    // downloadFile (url) {
    //   // window.location.href = process.env.VUE_APP_BASE_API + '/profile' + url
    // },
    // 附件操作
    changeFile (id, name) {
      this.fileList.push(id);
      this.form.attachmentIds = this.fileList;
      // this.$set(this.form.attachments, this.form.attachments.length, { fileName: name, fileId: id })
      // this.form.attachments.push({ fileName: name, fileId: id })
    },
    removeFileList (id) {
      this.form.attachmentIds = this.form.attachmentIds.filter(
        item => item != id
      );
      this.form.attachments = this.form.attachments.filter(
        item => item.fileId != id
      );
    },
    checkSelect (row, index) {
      let isChecked = true;
      if(row.status){
        isChecked = false;
      }
      return isChecked;
    },
    handlePreview (row) {
      this.filePreview(row.fileName, row.storagePath);
    },
    tableSortChange (column) {
      this.queryParams.pageNum = 1;

      if (column.order === "descending") {
        this.queryParams.sortBy = column.prop;
        this.queryParams.order = "desc";
      } else {
        this.queryParams.sortBy = column.prop;
        this.queryParams.order = "asc";
      }
      this.getList();
    }
  }
};
</script>
<style lang="scss" scoped>
.tatletitle {
  margin: 0 20px;
}
.a-style {
  color: #409eff;
}

/deep/.el-table .cell {
  .el-date-editor.el-input,
  .el-date-editor.el-input__inner {
    width: 90%;
  }
}
</style>
